package com.kyxx.topics.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.MyCommonTitle;
import com.loopj.android.http.RequestParams;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2016/7/21.
 */
public class UserRegisterActivity extends Activity implements View.OnClickListener{
    private MyCommonTitle myCommonTitle;
    private EditText ed_username, ed_mobile, ed_code, ed_password;
    private TextView btn_submit, btn_send_code;
    private String username, mobile, code, password;
    private int status;
    private static String APPKEY = "1770c6f012dda";
    private static String APPSECRET = "8196301ef118a8d76c717c190c51ecfa";
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        type = getIntent().getStringExtra("type");
        setContentView(R.layout.activity_user_register);

        // 初始化短信验证
        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);

        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_myTitle);

        ed_mobile = (EditText) findViewById(R.id.ed_mobile);// 用户名
        ed_code = (EditText) findViewById(R.id.ed_code);// 验证码
        ed_password = (EditText) findViewById(R.id.ed_pwd);// 密码
        btn_submit = (TextView) findViewById(R.id.btn_submit);// 确认
        btn_send_code = (TextView) findViewById(R.id.btn_send_code);// 获取验证码

        if (type.equals("register")) {
            myCommonTitle.setTitle("注册");
            btn_submit.setText("注册");
        } else if (type.equals("forget_pwd")) {
            myCommonTitle.setTitle("忘记密码");
            btn_submit.setText("重置密码");
        }
        btn_send_code.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        mobile = ed_mobile.getText().toString().trim();
        code = ed_code.getText().toString().trim();
        password = ed_password.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_send_code:
                if (!TextUtil.isMobile(mobile)) {
                    Tools.toast(UserRegisterActivity.this, "手机号码格式不正确！");
                    return;
                }
                /* 发送手机验证码 */
                btn_send_code.setOnClickListener(null);
                new MyCount(60000, 1000).start();// 一分钟倒计时
                SMSSDK.getVerificationCode("86", mobile);
                break;
            case R.id.btn_submit:
                if (!TextUtil.isCode(code, 4)) {
                    Tools.toast(UserRegisterActivity.this, "验证码格式不对！");
                    return;
                }
                if (StringUtil.isEmpty(mobile)) {
                    Tools.toast(UserRegisterActivity.this, "手机号码不能为空！");
                    return;
                }
                if (StringUtil.isEmpty(password)) {
                    Tools.toast(UserRegisterActivity.this, "密码不能为空！");
                    return;
                }
                if (!TextUtil.isPasswordLengthLegal(password)) {
                    Tools.toast(UserRegisterActivity.this, "密码长度合法性校验6-20位任意字符");
                    return;
                }
//                MyRequestDailog.showDialog(UserRegisterActivity.this, "");
                SMSSDK.submitVerificationCode("86", mobile, ed_code.getText().toString().trim());
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("result", "result=" + result);
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                    // Tools.toast(UserRegisterActivity.this, "提交验证码成功");
                    if (type.equals("register")) {
                        registerNewUser();
                    } else if (type.equals("forget_pwd")) {
                        resetPassWord();
                    }
                    // uu_password.setFocusable(true);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Tools.toast(UserRegisterActivity.this, "验证码已经发送");
                }
            } else {
//                MyRequestDailog.closeDialog();
                ((Throwable) data).printStackTrace();
                // int resId = getStringRes(UserRegisterActivity.this,
                // "smssdk_network_error");
                Tools.toast(UserRegisterActivity.this,
                        event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证码频繁，请稍后再试！" : "验证码错误");
                // if (resId > 0) {
                // Tools.toast(UserRegisterActivity.this, resId + "");
                // }
            }
        }

        /**
         * 提交信息，调用注册接口 ================= 此处区分是注册还是忘记密码,调用不同的接口=========================
         */
        private void registerNewUser() {
            RequestParams params = new RequestParams();
            params.put("Password", password);
            params.put("Mobile", mobile);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("Password", password);
//            jsonObject.put("Mobile", mobile);
//            StringEntity s = null;
//            try {
//                s = new StringEntity(jsonObject.toString(), "utf-8");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
            RestClient.post(UrlUtils.REGISTER, params, UserRegisterActivity.this, new ResponseListener(UserRegisterActivity.this,true) {
                        @Override
                        public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

                        }

                        @Override
                        public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                            super.failed(arg0, arg1, result);
                        }
                    }
            );
        }

        /**
         * 重置密码
         */
        private void resetPassWord() {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("Mobile", mobile);
//            jsonObject.put("Password", password);
//            StringEntity s = null;
//            try {
//                s = new StringEntity(jsonObject.toString(), "utf-8");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
            RequestParams params = new RequestParams();
            params.put("Password", password);
            params.put("Mobile", mobile);
            RestClient.post(UrlUtils.RESETPSW, params, UserRegisterActivity.this, new ResponseListener(UserRegisterActivity.this,true) {

                        @Override
                        public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

                        }

                        @Override
                        public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                            super.failed(arg0, arg1, result);
                        }
                    }
            );
        }
    };

    /* 定义一个倒计时的内部类 */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btn_send_code.setText("获取验证码");
            btn_send_code.setOnClickListener(UserRegisterActivity.this);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_send_code.setText(millisUntilFinished / 1000 + "秒");
        }
    }
}

